<?php

namespace frontend\modules\business\controllers\user;

use common\components\Upload;
use common\models\business\BusinessContract;
use common\models\business\BusinessFarmers;
use common\models\business\BusinessInspection;
use common\models\business\BusinessPig;
use common\models\business\BusinessPigFile;
use common\models\business\BusinessVariety;
use common\models\shop\ShopRaisingOrder;
use frontend\controllers\BaseMobileController;
use yii\db\Query;
use yii\helpers\Url;


/**
 * 认养仔猪订单相关
 */
class PigOrderController extends BaseMobileController
{



    /**
     * @return string
     * 我的仔猪
     */
    public function actionIndex()
    {

        $status = \Yii::$app->request->get('status');
        $query = (new Query())->select('o.refundfail_remark,p.id as pigid,o.id,o.ordersn as no,o.pigvariety as title,o.price,p.photo as img,p.status as pstatus,o.status')
            ->from(ShopRaisingOrder::tableName().' as o')
            ->leftJoin(BusinessPig::tableName().' as p','p.id=o.pigid');
        if(!is_null($status)){
            if($status == 3){
                $orderlist = $query->where('o.userid=:uid and o.status in(3,4,5)',[':uid'=>$this->user['userid']])
                    ->all();
            }else{
                $orderlist = $query->where('o.userid=:uid and o.status=:status',[':uid'=>$this->user['userid'],':status'=>$status])
                    ->all();
            }
        }else{
            $orderlist = $query->where('o.userid=:uid',[':uid'=>$this->user['userid']])
                ->all();
        }


        foreach ($orderlist as $key => $row){
            $totalnum = 0;
            $orderlist[$key]['oldstatus'] = $row['status'];
            $orderlist[$key]['status'] = ShopRaisingOrder::$statues[$row['status']];
            $orderlist[$key]['num'] = '1头';
            $orderlist[$key]['totalprice'] = $row['price'];
            $orderlist[$key]['cost'] = $row['price'];
            $orderlist[$key]['img'] = Upload::checkGetUrl($row['img'],false,'img');
        }

        return $this->render('@template/mobile/pigs_orderlist.html',[
            'orderlist' => \GuzzleHttp\json_encode($orderlist),
            'status' => $status
        ]);
    }



    /**
     * @return string
     * 猪详情
     */
    public function actionPigsDetail($id)
    {
        //取出仔猪信息
        $pig = (new Query())->from(BusinessPig::tableName().' as p')
            ->select('p.id,p.status,p.batch,p.no,p.photo,p.batch,p.intime,p.headperson as owner,liveryname as operator,p.killplace as slaughterhouse,v.title as type,v.descripation as typeinfo,f.address,f.photo as favatar,pf.father as f_no,pf.mathor as m_no,c.partyA,c.no as contract_no')
            ->addSelect('pf.matherphoto as m_img,fatherphoto as f_img,f.pighousephoto')
            ->leftJoin(BusinessFarmers::tableName().' as f','p.livery=f.id')
            ->leftJoin(BusinessVariety::tableName().' as v','v.id=p.varietyid')
            ->leftJoin(BusinessPigFile::tableName().' as pf','pf.id=p.fileid')
            ->leftJoin(BusinessContract::tableName().' as c','c.id=pf.constract_id')
            ->where('p.id=:id',[':id'=>$id])
            ->one();


        //处理数据
        $pig['oldstatus'] = $pig['status'];
        $pig['status'] = BusinessPig::$statues[$pig['status']];
        $pig['favatar'] = Upload::checkGetUrl($pig['favatar']);
        $pig['m_img'] = Upload::checkGetUrl($pig['m_img']);
        $pig['f_img'] = Upload::checkGetUrl($pig['f_img']);
        $pig['surroundings'] = Upload::checkGetUrl($pig['pighousephoto'],true);
        $pig['period'] = intval((time()-$pig['intime'])/3600*24).'天';

        //取出巡检记录
        $records = BusinessInspection::find()->select('id,createtime,business_person')->where('pigid=:pigid',[':pigid'=>$id])->asArray()->all();
        foreach ($records as $key => $row)
        {
            $records[$key]['title'] = '于'.date('Y-m-d',$row['createtime']).'巡检';
            $records[$key]['no'] = $key+1;
            $records[$key]['who'] = $row['business_person'];
            $records[$key]['url'] = \yii\helpers\Url::to(['/shop/site/from-detail','recordid'=>$row['id']]);
        }
        $pig['records'] = $records;


        //取出banner
        $banner = Upload::checkGetUrl($pig['photo'],true);

        return $this->render('@template/mobile/mypigsdetail.html',[
            'detail' => \GuzzleHttp\json_encode($pig),
            'banner' => \GuzzleHttp\json_encode($banner)

        ]);

    }


    /**
     * @return array
     * 取消订单
     */
    public function actionCancal()
    {
        $postdata = \Yii::$app->request->post();
        $res = \Yii::$app->db->createCommand()->update(ShopRaisingOrder::tableName(),['status'=>ShopRaisingOrder::STATUS_CANCAL],'id=:id',[':id'=>$postdata['id']])
            ->execute();
        return $res?$this->jsonMsg():$this->jsonMsg('取消失败',1);
    }


    /**
     * @return array
     * 申请退款
     */
    public function actionRefund()
    {
        $postdata = \Yii::$app->request->post();
        $res = \Yii::$app->db->createCommand()->update(ShopRaisingOrder::tableName(),['status'=>ShopRaisingOrder::STATUS_REFOUND],'id=:id',[':id'=>$postdata['id']])
            ->execute();
        return $res?$this->jsonMsg('已发起申请，请等待审核'):$this->jsonMsg('已发起申请失败',1);
    }












}